import React, {
  createRef,
  useCallback,
  useEffect,
  useRef,
  useState,
} from "react";
import classNames from "classnames";
import { debounce } from "debounce";
import { AtSearchBar } from "taro-ui";
import Taro, { useReachBottom } from "@tarojs/taro";
import "./index.scss";
import { AtFileSearchBar, FileSearchBar } from "../file-search-bar";
import fileFolder from "../../../assets/file-folder.png";
import NoFile from "../../../assets/no-file.png";
import { FileItem as IFileItem, IFile } from "../../../../src/interfaces";
import { fetchFiles, fetchStsToken } from "../../../../src/api/file-tab";
import {
  matchSuffixType,
  matchType,
} from "../../../../src/utils/check-file-type";
import {
  getFileSizeText,
  getOssThumbnail,
  getOssUrl,
  useDebounce,
} from "../../../../src/utils";
import { SearchBar } from "../../../../src/components/search-bar";
import { NoRecord } from "../../../../src/components/no-record";
import { FileImage } from "../../../../src/components/img";
// import Vconsole from "vconsole";

// const vConsole = new Vconsole();
export const FileItem = ({
  onClick,
  ...file
}: IFileItem & { onClick: (id: IFileItem) => void }) => {
  const icon =
    matchSuffixType(file.extensionName, +file.type) ||
    matchType["icon-a-CannotPreview"];
  return (
    <div className="file-card-item" onClick={() => onClick(file)}>
      <div className="preview-container">
        {file.thumbnail ? (
          <FileImage
            style={{ width: "100%", maxHeight: "100%" }}
            src={getOssThumbnail(file.thumbnail)}
            icon={icon}
          />
        ) : (
          <span className={`iconfont ${icon}`}></span>
        )}
      </div>
      <div className="description">
        <div className="name ellipsis">{file.name}</div>
        <div className="info">
          {+file.type === 200
            ? `${file.fileCount}个文件`
            : +file.type === 600
            ? "-"
            : getFileSizeText(file.size)}
        </div>
      </div>
    </div>
  );
};

export const FileComponent = ({
  tab,
  channelId: propsChannelId,
}: {
  tab?: boolean;
  channelId?: string;
}) => {
  const { router } = Taro.getCurrentInstance();
  const [firstFetched, setFirstFetched] = useState(false);
  const filesRef = createRef<HTMLDivElement>();

  const spaceId = router?.params.spaceId || "";
  const dirIds = router?.params.dirId || "";
  const accessKey = router?.params.accessKey || "";
  const channelId = router?.params.channelId || propsChannelId || "";
  const [searchValue, setSearchValue] = useState("");
  const [loading, setLoading] = useState(false);
  const [fileList, setFileList] = useState<IFileItem[]>([]);
  /** 页码 */
  const curPage = useRef(0);
  /** 是否已加载完成 */
  const fetchAll = useRef(false);
  const getMoreFiles = useDebounce(async (_search?: string) => {
    if (!router || !router.params) return;
    const ids = dirIds.split(",") || [];
    const dirId = ids[ids.length - 1] || "root";
    let search = searchValue;
    let searchPage = curPage.current;
    if (typeof _search === "string") {
      search = _search || "";
      searchPage = 0;
    }
    const { code, data, message } = await fetchFiles(
      spaceId,
      channelId,
      dirId,
      accessKey,
      {
        conditions: [
          {
            key: "name",
            value: [search],
          },
        ],
        sorts: [
          {
            key: "created_at",
            value: "desc",
          },
        ],
        current: searchPage + 1,
        pageSize: 10,
      }
    );
    Taro.hideLoading();
    setLoading(false);
    setFirstFetched(true);
    if (code !== 0) return;
    let newFileList: IFileItem[] = [];
    if (data.current === 1) {
      newFileList = data.list;
    } else if (data.current - 1 === curPage.current) {
      curPage.current = data.current;
      newFileList = fileList?.concat(data.list) || [];
    }
    curPage.current = data.current;
    setFileList(newFileList);

    console.log("getMoreFiles -> newFileList", newFileList);
    if (newFileList.length >= data.total) {
      fetchAll.current = true;
    }
  }, 500);

  const handleInput = (v: string) => {
    setSearchValue(v);
    getMoreFiles(v);
  };
  useEffect(() => {
    /** 获取sts token */
    const init = async () => {
      setLoading(true);
      Taro.showLoading();
      const { code, data, message } = await fetchStsToken(
        spaceId,
        channelId,
        accessKey
      );
      localStorage.setItem("stsToken", JSON.stringify(data));
      getMoreFiles();
    };
    init();
  }, []);
  useEffect(() => {
    if (!filesRef.current) return;
    const container = filesRef.current.parentElement;
    if (!container) return;
    container.onscroll = (e) => {
      const { scrollHeight, offsetHeight, scrollTop } =
        e.target as HTMLDivElement;
      if (scrollHeight - offsetHeight - scrollTop > 5) {
        if (fetchAll.current) return;
        getMoreFiles();
      }
    };
    return () => {
      container.onscroll = () => {};
    };
  }, [getMoreFiles]);
  /** 跳转 */
  const handleClick = (file: IFileItem) => {
    if (file.type === 200) {
      const ids = (dirIds.split(",") || []).filter((i) => i);
      Taro.navigateTo({
        url: `/pages/file/index?spaceId=${spaceId}&channelId=${channelId}&filename=${
          file.name
        }&dirId=${ids.concat(file.id).join(",")}`,
      });
    } else if (file.type === 500) {
      // 预览
      const type = matchSuffixType(file.extensionName, file.type);

      Taro.navigateTo({
        url: `/pages/file-preview/index?spaceId=${spaceId}&channelId=${channelId}&fileId=${
          file.id
        }&canPreview=${!!type}&accessKey=${accessKey}`,
      });
    } else {
      // 链接
      Taro.navigateTo({
        url: `/pages/file-preview/index?spaceId=${spaceId}&channelId=${channelId}&fileId=${
          file.id
        }&name=${file.name}&urlLink=${encodeURIComponent(file.urlLink || "")}`,
      });
    }
  };
  if (loading) return null;
  return (
    <div
      className={classNames("file-component", "clearfix", { tab })}
      ref={filesRef}
    >
      {/* <FileSearchBar value={searchValue} onInput={setSearchValue} /> */}
      {/* <AtFileSearchBar value={searchValue} onInput={handleInput} /> */}
      <div>
        {console.log("fileList", fileList)}
        {console.log("firstFetched", firstFetched)}
        <SearchBar
          className="file-search-bar"
          value={searchValue}
          onInput={handleInput}
        />
        {fileList?.length > 0 ? (
          <div className="file-container">
            {fileList.map((file) => {
              return <FileItem key={file.id} {...file} onClick={handleClick} />;
            })}
          </div>
        ) : (
          firstFetched && <NoRecord img={NoFile} text="暂无文件" />
        )}
      </div>
    </div>
  );
};
